<template>
	<view>
		<st-mc-framework :navTitle="ModuleTitle" @changeLevel="changeLevel" ref="framework"
			@AddModuleData_select='AddModuleData_select'>

			<template #content>
				<view class="content" style="width: 100%;height: 100%;">
					<view class="contentBox" style="flex: 1;">
						<view class="container TitleImageRelative">
							<view class="titleImage">
								<image src="../css/img/shenhe.png" v-show="readOnlyShow">
								</image>
							</view>

							<u--form class="u_form" labelPosition="left" :model="baseFormData" ref="uForm">
								<u-row justify="space-between" gutter="20">
									<u-col span="4">
										<u-form-item labelWidth="auto" label="报工类型:" @click="addDefine1">
											<u--input v-model="baseFormData.Define1Name" placeholder="请选择报工类型" readonly
												border="none"></u--input>
											<u-icon slot="right" name="arrow-right"></u-icon>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="生产日期:" @click="AddSCDate()" required>
											<u--input v-model="baseFormData.SCDate" placeholder="请选择生产日期" readonly
												border="none"></u--input>
											<u-icon slot="right" name="arrow-right"></u-icon>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="工序:" required>
											<u--input v-model="baseFormData.ProcedureName" placeholder="自动带出工序" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
								</u-row>


								<u-row justify="space-between" gutter="20">
									<u-col span="4">
										<u-form-item labelWidth="auto" label="报工数量:" required>
											<u--input v-model="baseFormData.FSumQty" placeholder="自动带出报工数量" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="合格数量:" required>
											<u--input v-model="baseFormData.FDailyQtt" placeholder="请输入合格数量"
												type='number' @input="addAmount('合格')" :readonly='readOnlyShow'
												border="none"></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="不合格数量:" required>
											<u--input v-model="baseFormData.FNgQty" placeholder="由不良报废自动带出" readonly
												type='number' border="none"></u--input>
										</u-form-item>
									</u-col>
								</u-row>


								<u-row justify="space-between" gutter="20">
									<u-col span="4">
										<u-form-item labelWidth="auto" label="生产人员:" required>
											<u--input v-model="baseFormData.FProcessManName" placeholder="自动带出生产人员"
												readonly border="none"></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="审核状态:">
											<u--input v-model="baseFormData.ApproveName" placeholder="自动带出审核状态" readonly
												border="none"></u--input>

										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="审核人:">
											<u--input v-model="baseFormData.Approver" placeholder="自动带出审核人" readonly
												border="none"></u--input>

										</u-form-item>
									</u-col>
								</u-row>



								<u-row justify="start" gutter="20">
									<u-col span="4">
										<u-form-item labelWidth="auto" label="审核时间:">
											<u--input v-model="baseFormData.ApproveTime" placeholder="自动带出审核时间" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>

									<u-col span="4">
										<u-form-item labelWidth="auto" label="计件计时:" @click="AddPieceTime">
											<u--input v-model="baseFormData.PieceTime1" placeholder="请选择计时计件" readonly
												border="none"></u--input>
											<u-icon slot="right" name="arrow-right"></u-icon>
										</u-form-item>
									</u-col>

									<!-- 动态控制工时和备注的显示位置 -->
									<u-col v-if="baseFormData.PieceTime1=='计时'" span="4">
										<u-form-item labelWidth="auto" label="工时:">
											<u--input v-model="baseFormData.ManHour" placeholder="请输入工时"
												:readonly='readOnlyShow' border="none"></u--input>
										</u-form-item>
									</u-col>

									<!-- 当工时隐藏时，备注占用工时的位置 -->
									<u-col v-else span="4">
										<u-form-item labelWidth="auto" label="备注:">
											<u--input v-model="baseFormData.FRemarks" placeholder="请输入备注"
												:readonly='readOnlyShow' border="none"></u--input>
										</u-form-item>
									</u-col>
								</u-row>

								<!-- 第二个u-row中白夜班保持原位置，备注在工时显示时不出现 -->
								<u-row justify="start" gutter="20">
									<u-col span="4" v-if="baseFormData.PieceTime1=='计时'">
										<!-- 当工时显示时，此备注不显示 -->
										<u-form-item labelWidth="auto" label="备注:">
											<u--input v-model="baseFormData.FRemarks" placeholder="请输入备注"
												:readonly='readOnlyShow' border="none"></u--input>
										</u-form-item>
									</u-col>

									<u-col span="4">
										<u-form-item labelWidth="auto" label="白夜班:">
											<u--input v-model="baseFormData.ShiftName" placeholder="白夜班" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>

									<u-col span="4">
										<u-form-item labelWidth="auto" label="模具:">
											<u--input v-model="baseFormData.MoldNO" placeholder="自动带出模具" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
								</u-row>



							</u--form>
						</view>
						<view class="table" style="text-align: center;margin: auto;">
							<table>
								<tr>

									<th width='20%'>派工单编号</th>
									<th width='42%'>产品名称</th>
									<th width='8%'>派工数</th>
									<th width='8%'>完成数</th>
									<th width='10%'>可报工数</th>
									<th width='12%'>未审核报工数</th>

								</tr>
								<tr>
									<td>
										<u--textarea v-model="baseFormData.PGBillNo" autoHeight border="none" disabled
											class="fixed-textarea"></u--textarea>
									</td>

									<td>
										<view class="td_view">
											<view class="ListTdDiv">
												<text>{{baseFormData.ProductName}}</text>
											</view>

											<view class="SOPView">
												<u-button size="small" text="查看SOP" @click="addSOP"></u-button>
											</view>
										</view>

									</td>
									<td>
										<u--textarea v-model="baseFormData.FPlanQty" autoHeight border="none" disabled
											class="fixed-textarea"></u--textarea>
									</td>
									<td>
										<u--textarea v-model="baseFormData.WCQty" autoHeight border="none" disabled
											class="fixed-textarea"></u--textarea>
									</td>
									<td>
										<u--textarea v-model="baseFormData.ReportQty" autoHeight border="none" disabled
											class="fixed-textarea"></u--textarea>
									</td>
									<td>
										<u--textarea v-model="baseFormData.NotApproveQty" autoHeight border="none"
											disabled class="fixed-textarea"></u--textarea>
									</td>
								</tr>
							</table>

						</view>

					</view>
					<view class="bottomBtnsAll">
						<button class="button0" block @click="badnum" v-show="showBadButton">
							不良输入
						</button>
						<button class="button1" block @click='exception'>
							异常提交
						</button>
						<button class="button3" block @click="submit('保存')"
							v-show='ApproveButton=="保存"||ApproveButton=="未审核"'> 报工提交 </button>
						<button class="button2" block @click='continueWork'
							v-show='ApproveButton!="保存"&&baseFormData.ReportQty!=0'>
							继续报工
						</button>
						<!-- <button v-if="ApproveBack('审核')" class="button2" block @click='toexamine'
							v-show='baseFormData.ApproveName=="未审核"&&ApproveButton=="未审核"'>
							审核
						</button> -->

					</view>


				</view>
			</template>
		</st-mc-framework>
		<u-icon name="arrow-left" size="28" class="arrow_left" @click="rightshow=true"></u-icon>


		<u-picker :show="JYJGshow" :columns="columns" @confirm="JYJGconfirm" @cancel='JYJGshow=false'
			@close='JYJGshow=false'></u-picker>
		<u-action-sheet :actions="Resultlist" :show="Resultshow" @select="ResultClick"
			@close="Resultshow=false"></u-action-sheet>


		<u-toast ref="uToast"></u-toast>


		<u-action-sheet :actions="MoludList" :show="MoludShow" @select="MoludClick"
			@close="MoludShow=false"></u-action-sheet>

		<u-action-sheet :actions="Define1List" :show="Define1Show" @select="Define1Click"
			@close="Define1Show=false"></u-action-sheet>

		<u-action-sheet :actions="PieceTimeList" :show="PieceTimeShow" @select="PieceTimeClick"
			@close="PieceTimeShow=false"></u-action-sheet>

		<u-action-sheet :actions="exceptionList" :show="exceptionShow" @select="exceptionClick"
			@close="exceptionShow=false"></u-action-sheet>

		<u-datetime-picker :show="Timeshow" v-model="value1" mode="date" @close="Timeshow = false"
			@cancel='Timeshow = false' @confirm='pickerConfirm'></u-datetime-picker>


		<u-action-sheet :actions="ShiftNameList" :show="ShiftNameShow" @select="ShiftNameClick"
			@close="ShiftNameShow=false"></u-action-sheet>
		<u-popup :show="rightshow" mode="right" @close="rightclose" @open="rightopen" :width="500" class="rightshowView"
			:safeAreaInsetTop='true'>
			<view class="table tableTow">
				<table>
					<tr>
						<th width='8%'>
							<checkbox-group @change="toggleSelectAll" v-show="selectedItems.length>0">
								<checkbox value="all" :checked="isAllSelected"></checkbox>
							</checkbox-group>
						</th>
						<th width='30%'>报工日期</th>
						<th>生产人员</th>
						<th>报工数</th>
						<th>良品数</th>
						<th>不良品数</th>
						<th>审核状态</th>
					</tr>
					<tbody>
						<tr v-for="(item,index) in DailyOutputList" @click="sortrightclose(item)">
							<td width='8%'>
								<checkbox-group @change="toggleSelect(item)" @click.stop>
									<checkbox :checked="selectedItems.includes(item.id)"
										:disabled="shouldDisableCheckbox(item)"></checkbox>
								</checkbox-group>
							</td>
							<td>
								<view class="ListTdDiv"> <text>{{item.BillDate}}</text></view>
							</td>
							<td>
								<view class="ListTdDiv"> <text>{{item.FProcessManName}}</text></view>
							</td>
							<td>
								<view class="ListTdDiv"> <text>{{item.FSumQty}}</text></view>
							</td>
							<td>
								<view class="ListTdDiv"> <text>{{item.FDailyQtt}}</text></view>
							</td>
							<td>
								<view class="ListTdDiv"> <text>{{item.FNgQty}}</text></view>
							</td>
							<td>
								<view class="ListTdDiv"> <text>{{item.Approve?'已审核':'未审核'}}</text></view>
							</td>
						</tr>
					</tbody>

				</table>

			</view>

			<view class="u-popup——view" v-if="ApproveBack('审核')&&ToExamineShow">
				<u-button type="primary" :text="ToExamineName" @click='Pltoexamine'></u-button>
			</view>
		</u-popup>






		<u-modal :show="modalshow" :title="modaltitle" width="400" @confirm='modalconfirm'
			:showCancelButton="modaltitle!='报错'" :confirmText='confirmText' :cancelText="cancelText"
			@cancel='modalcancel'>
			<view class="slot-content">
				{{modalcontent}}
			</view>
		</u-modal>
		<m-loading :text="loadingName" v-model="showMLoading" :showClose="false"
			maskBackgroundColor="rgba(0,0,0,0.3)"></m-loading>
	</view>
</template>

<script>
	const open = uni.requireNativePlugin("Html5App-openFile");
	import formItem from '../../uni_modules/uview-ui/libs/config/props/formItem';
	import {
		getTimeStamp,
		getFormatDateTime,
		getBefore7DateTime,
		formatDateTime,
		navigateMixin,
		baseAddModuleData_select,
		getchangeLevel
	} from '@/st_mes_zs/common/base.js';

	export default {
		mixins: [navigateMixin, baseAddModuleData_select],
		data() {
			return {

				loadingName: '',
				readOnlyShow: false,
				confirmText: '确认',
				cancelText: '取消',



				initData: {},
				initObj: {},
				baseFormDataList: {},
				baseFormData: {
					DeviceID: null,
					DeviceName: '',
					FSumQty: null,
					FDailyQtt: null,
					// NewFNgQty: 0,
					FNgQty: '',
					PieceTime1: '',
					PieceTime: 0,
					JobOrderID: 0,
					PGBillNo: 0,
					BillDate: ":",
					ProductID: 0,
					ProductName: "",
					ReportQty: 0,
					FPlanQty: 0,
					WCQty: 0,
					DailyQtt: null,
					ProcedureName: "",
					JobPROCID: 0,
					JobDocTypeID: 0,
					Define1: '',
					Define1Name: '',
					TypeName: "",
					FProcessMan: '',
					FProcessManName: '',
					FWorkshopID: 0,
					SCDate: '',
					ProcedureID: 0,
					WoOrderID: 0,
					EquipmentName: '',
					EquipmentID: 0,
					ShiftID: 0,
					ShiftName: '',
					InspectionID: 0,
					ApproveName: '',
					FRemarks: '',
					MoludID: null,
					MoldNO: '',
				},
				value1: Number(new Date()),
				Timeshow: false,
				sexs: [{
					text: '合格',
					value: 1
				}, {
					text: '不合格',
					value: 0
				}],
				tableData: [{
					name: '',
					QCEmplName: '',
					num: 3000

				}],
				ShiftNameList: [{
						name: '白班',
						id: 1
					},
					{
						name: '夜班',
						id: 2
					}
				],
				ShiftNameShow: false,
				routeIndex: 0,
				JYJGshow: false,
				columns: [
					['合格', '不合格']
				],
				JYJGshowIndex: 0,
				Resultshow: false,
				Resulttitle: '',
				Resultlist: [],

				PieceTimeShow: false,
				PieceTimeList: [{
						name: '计时',
						id: 1
					},
					{
						name: '计件',
						id: 0
					}
				],
				Define1Show: false,
				Define1List: [],
				someData: null,
				rightshow: false,
				JobPROCID: null,
				DailyOutputList: [],

				exceptionShow: false,
				exceptionList: [{
						name: '设备异常',
						id: 0
					},
					{
						name: '模具异常',
						id: 1
					},
					{
						name: '工艺异常',
						id: 2
					},
					{
						name: '品质异常',
						id: 3
					},
				],
				MoludShow: false,
				MoludList: [],


				disabled: false,
				ApproveButton: '保存',
				BtnApprove: [], // 权限数组
				selectedIndexs: [],
				selectedList: [],
				ModuleTitle: '', //标题名称
				showMLoading: false, //是否加载
				loadingName: '正在加载中……', //加载名称
				modalshow: false, //提示显示
				modaltitle: '', //提示名称
				modalcontent: '', //提示内容
				FWorkshopID: null,
				selectedItems: [], // 存储选中行的索引
				ReviewShow: false, //审核按钮显示		
				ToExamineShow: false,
				ToExamineName: '',
			};
		},
		onShow() {

			uni.$on('refreshDetail', (res) => {
				this.getValue(res); // 调用目标方法
			});
			uni.$on('refreshList', () => {
				this.getList(); // 调用目标方法
			});
			uni.$on('refselfValue', (res) => {
				this.getselfValue(res); // 调用目标方法
			});
		},
		onUnload() {
			uni.$off('refreshDetail');
			uni.$off('refreshList');
			uni.$off('refselfValue');
		},
		computed: {
			showBadButton() {
				var that = this
				const {
					InspectionID,
					FDailyOutputID,

				} = that.baseFormData;
				// console.log(InspectionID);
				// console.log(FDailyOutputID);
				// console.log(that.readOnlyShow);
				// console.log(!InspectionID && !FDailyOutputID);
				// console.log(!that.readOnlyShow && FDailyOutputID);
				// console.log(that.readOnlyShow && InspectionID && FDailyOutputID);
				return (
					(InspectionID && !FDailyOutputID) ||
					(!InspectionID && !FDailyOutputID) ||
					(!that.readOnlyShow && FDailyOutputID) ||
					(that.readOnlyShow && InspectionID && FDailyOutputID)
				);
			},
			// isAllSelected() {
			// 	var AllList = this.DailyOutputList.filter(item => item.Approve != true)
			// 	return this.selectedItems.length === AllList.length && AllList.length > 0;
			// },
			isAllSelected() {
				// 筛选当前可操作的项（与选中项同状态）
				const referenceApprove = this.selectedItems.length > 0 ?
					this.DailyOutputList.find(item => item.id === this.selectedItems[0])?.Approve :
					null;
				const AllList = this.DailyOutputList.filter(item => item.Approve === referenceApprove);

				// 当可操作项存在且所有可操作项都被选中时，全选框才勾选
				return AllList.length > 0 && this.selectedItems.length === AllList.length;
			},
		},

		onReady() {
			var that = this
			uni.hideLoading();
			const {
				GuyueModule,
				UserInfo,
				appConfigInfo
			} = that.$store.state;
			const {
				MesBasicInfo
			} = GuyueModule;
			that.FWorkshopID = MesBasicInfo.FWorkshopID;
			that.ModuleTitle = appConfigInfo.ActiveModule.ModuleName

			let foundNode = null;
			for (const module of this.$store.state.appConfigInfo.ModuleInfo_All) {
				if (module.TreeTypeName === '生产派工') {
					for (const node of module.Node) {
						if (node.APFunName === '生产报工') {
							foundNode = JSON.parse(JSON.stringify(node));
							break; // 找到后立即退出内层循环  
						}
					}
					if (foundNode) {
						break;
					}
				}
			}
			this.BtnApprove = foundNode['IconApprove'];
		},
		onLoad(onload) {
			var that = this
			that.$safeStatus({
				payload: '其他', // 要传递的数据
			});
			console.log(onload);
			// 缓存状态引用
			const {
				GuyueModule,
				UserInfo,
				appConfigInfo
			} = this.$store.state;
			const {
				MesBasicInfo
			} = GuyueModule;
			// 统一处理加载状态
			const setLoading = (state) => this.showMLoading = state;
			console.log(onload);
			var iteminfo
			if (onload.item) {
				iteminfo = JSON.parse(onload.item)
				delete iteminfo.FNGQty; // 删除obj对象的age属性
				this.assignFormData(this.baseFormData, iteminfo);
				this.baseFormDataList = iteminfo
				if (onload.titleName && onload.titleName == '刷新') {
					that.readOnlyShow = iteminfo.ApproveName === '已审核' ? true : false;
					that.ApproveButton = iteminfo.ApproveName === '已审核' ? '已审核' : '未审核';
					return;
				}
			}
			console.log(that.baseFormData);
			// 主处理逻辑
			if (that.baseFormData.FDailyOutputID) {
				setLoading(true);
				this.queryList(that.baseFormData.FDailyOutputID);
				return;
			}

			this.addqueryList()
			setLoading(false);
		},
		onBackPress(options) { // 监听页面返回
			if (options.from == 'navigateBack') { // 通过点击路由返回
				return false;
			} else if (options.from == 'backbutton') { // 通过外置返回
				return true;
			}
		},
		methods: {
			shouldDisableCheckbox(item) {
				if (this.selectedItems.length === 0) return false;
				const currentApprove = item.Approve;
				// console.log(this.selectedItems);
				return this.selectedItems.some(selectedId => {
					const selectedItem = this.DailyOutputList.find(c => c.id === selectedId);
					return selectedItem?.Approve !== currentApprove;
				});
			},

			Pltoexamine() {
				var that = this;
				var Approve
				var msg
				var filteredData = this.DailyOutputList.filter(item =>
					that.selectedItems.some(id => id === item.id)
				)
				var filteredDatalist = filteredData.map(item => item.FDailyOutputID)
				var ids = filteredDatalist.join('~')
				if (ids) {
					that.selectedItems = []
					switch (this.ToExamineName) {
						case '审核':
							Approve = 1
							msg = '审核成功'
							break;
						case '取消审核':
							Approve = 0
							msg = '撤审成功'
							break;
					}
					var obj1 = {
						FDailyOutputID: ids,
						ApproveStatus: Approve,
					}
					that.Request.request('ApproveDailyOutput_pl', obj1, function(ret) {
						console.log(ret);
						if (ret.status == 200) {
							if (ret.data.ds && ret.data.ds.length > 0) {
								if (ret.data.ds[0].RZT && ret.data.ds[0].RZT == 500) {
									that.showModal('报错', ret.data.ds[0].RMS, '确认', '取消');
								} else {
									that.rightshow = false
									that.$refs.uToast.show({
										title: '提醒',
										type: 'success',
										message: msg
									})
									if (that.baseFormData.FDailyOutputID) {
										that.queryList(that.baseFormData.FDailyOutputID)
									} else {
										that.queryList(filteredDatalist[filteredDatalist.length - 1])
									}
								}
							} else {
								that.rightshow = false
								that.$refs.uToast.show({
									title: '提醒',
									type: 'success',
									message: msg
								})
								if (that.baseFormData.FDailyOutputID) {
									that.queryList(that.baseFormData.FDailyOutputID)
								} else {
									that.queryList(filteredDatalist[filteredDatalist.length - 1])
								}
							}
						}
					})
				} else {
					that.showModal('提醒', '请勾选需要审核/取消审核的报工单', '确认', '取消');
				}
			},

			modalcancel() {
				var that = this
				that.modalshow = false
				if (that.modaltitle == '通知') {
					that.AndSetStateData()
				}
			},
			modalconfirm() {
				var that = this
				that.modalshow = false
				if (that.modaltitle == '通知') {
					that.submit('退出')
				}
			},

			// 创建表单赋值工具函数
			assignFormData(target, defaults = {}) {
				Object.keys(defaults).forEach(key => {
					Vue.set(target, key, defaults[key]);
				});
				// console.log(this.baseFormData);
				this.$forceUpdate();
			},
			replaceFormData(target, source, defaults = {}) {
				Object.keys(defaults).forEach(key => {
					target[key] = source[key] || defaults[key];
				});
				this.$forceUpdate()
			},
			async AddModuleData_select(res) {
				try {
					const backDelta = await this.GetModuleData_select(res);
				} catch (error) {
					console.error('返回操作失败:');
				}
			},
			showModal(title, content, confirmText, cancelText) {
				this.confirmText = confirmText
				this.cancelText = cancelText
				this.modaltitle = title;
				this.modalcontent = content;
				this.modalshow = true;
			},

			ShiftNameClick(e) {
				const formDefaults = {
					ShiftName: e.name,
					ShiftID: e.id,
				};
				this.assignFormData(this.baseFormData, formDefaults)
				this.ShiftNameShow = false
			},
			ClickShift() {
				this.ShiftNameShow = true
			},

			getValue(payload) {
				var that = this;
				console.log(payload);
				that.showMLoading = false
				const {
					type,
					...data
				} = payload;
				if (payload === '返回') return;
				const typeHandlers = {
					'生产人员': () => ({
						FProcessMan: data.EmplID,
						FProcessManName: data.name,
					})
				};
				if (typeHandlers[type]) {
					Object.assign(that.baseFormData, typeHandlers[type]());
				}
				console.log(this.baseFormData);
				this.$forceUpdate()
			},


			addqueryList() {
				let that = this;
				const {
					GuyueModule,
					UserInfo,
					appConfigInfo
				} = this.$store.state;
				const {
					MesBasicInfo
				} = GuyueModule;
				const formDefaults = {
					FNgQty: 0,
					FDailyQtt: 0,
					EquipmentID: MesBasicInfo.warehouse.EquipmentID,
					EquipmentName: MesBasicInfo.warehouse.EquipmentName,
					FProcessManName: UserInfo.EmplName,
					FProcessMan: UserInfo.EmplID,
					FRemarks: '',
					ShiftID: MesBasicInfo.ShiftObj.ShiftID,
					ShiftName: MesBasicInfo.ShiftObj.ShiftName,
					SCDate: getFormatDateTime(new Date()),
					PieceTime1: '计件',
					PieceTime: 0,
				};
				console.log(formDefaults);
				that.assignFormData(that.baseFormData, formDefaults)
				this.GetBGType()
			},
			continueWork() {
				let that = this;
				that.baseFormData = that.baseFormDataList
				that.addqueryList()

				const formDefaults = {
					InspectionID: 0,
					FDailyOutputID: 0,
					FSumQty: null,
					ApproveTime: '',
					ApproveName: '',
					Approver: '',
					FDailyOutputDeID: 0,

				};
				that.assignFormData(that.baseFormData, formDefaults)
				that.ApproveButton = '保存'
				that.readOnlyShow = false
				that.$forceUpdate()
			},
			GetBGType() {
				let that = this;
				var obj = {
					JobPROCID: that.baseFormData.JobPROCID,
					JobOrderID: that.baseFormData.JobOrderID,
				}
				that.Request.request('PGD_GetBGType', {}, function(ret) {
					// console.log(ret);
					// console.log(that.baseFormData.JobDocTypeID);
					// if (ret.data.ds[0].JobDocTypeID == 3) {
					// 	that.$set(that.baseFormData, 'Define1Name', '报工单')
					// } else {
					// 	that.$set(that.baseFormData, 'Define1Name', '超额报工')
					// }
					// that.$set(that.baseFormData, 'Define1', ret.data.ds[0].JobDocTypeID)
					that.$forceUpdate()
				})
			},


			ApproveBack(str) {
				let that = this;
				let Type = false;
				if (that.BtnApprove.length) {
					Type = that.BtnApprove.some(item => {
						return item.MenuName == str
					})
				}
				return Type;
			},

			getList() {

			},

			openBaseScreen(str) {
				var that = this;
				uni.hideKeyboard(); //隐藏软键盘
				if (!that.readOnlyShow) {
					var obj;
					var name
					name = that.baseFormData.ProcedureName.slice(-2)
					if (str == '生产人员') {
						obj = {
							cmd: 'getSCEmplList',
							type: str,
							serverSearch: {
								isPaging: true, //是否分页
								pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中		
								searchShow: false, //是否查询
								searchKey: 'searchKey', //搜索关键词，应包含在param中
								showText: 'EmplName', //查询结果显示的字段
							},
							param: {
								JobName: name,
								PageIndex: 1,
								PageSize: 30
							}
						}
					}
					uni.navigateTo({
						url: `../common/baseScreen?obj=${JSON.stringify(obj)}`,
						animationType: 'slide-in-right',
						animationDuration: 300
					});
				}
			},
			addAmount(str) {
				var that = this
				const formDefaults = {
					FSumQty: that.baseFormData.FDailyQtt,
				};
				that.assignFormData(that.baseFormData, formDefaults)

			},
			// 修正后的全选方法
			// toggleSelectAll(e) {
			// 	const checked = e.detail.value.includes('all')

			// 	var ApproveShow = this.ToExamineName == '取消审核' ? true : null
			// 	var AllList = this.DailyOutputList.filter(item => item.Approve == ApproveShow)
			// 	const pageIds = AllList.map(item => item.id)
			// 	if (checked) {
			// 		this.selectedItems = [...new Set([...AllList, ...pageIds])]
			// 	} 
			// 	else {
			// 		this.selectedItems = this.selectedItems.filter(id => !pageIds.includes(id))
			// 	}
			// 	if (this.selectedItems.length === 0) {
			// 		this.ToExamineShow = false
			// 		this.ToExamineName = ''
			// 	}

			// },
			// 全选/取消全选方法
			toggleSelectAll(e) {
				const checked = e.detail.value.includes('all');

				// 关键：根据当前操作类型筛选可操作的项
				// 如果已有选中项，以第一个选中项的审核状态作为基准（限制同类型操作）
				// 如果没有选中项，默认筛选"未审核"项（首次全选默认操作"审核"）
				const referenceApprove = this.selectedItems.length > 0 ?
					this.DailyOutputList.find(item => item.id === this.selectedItems[0])?.Approve :
					null;

				// 筛选出符合当前操作类型的项（只能操作同状态的项）
				const AllList = this.DailyOutputList.filter(item => item.Approve === referenceApprove);
				const pageIds = AllList.map(item => item.id); // 提取可操作项的ID数组

				if (checked) {
					// 全选：选中所有可操作项的ID
					this.selectedItems = [...new Set(pageIds)];
				} else {
					// 取消全选：移除所有可操作项的ID
					this.selectedItems = this.selectedItems.filter(id => !pageIds.includes(id));
				}

				// 更新操作按钮状态
				if (this.selectedItems.length === 0) {
					this.ToExamineShow = false;
					this.ToExamineName = '';
				} else {
					// 根据选中项的状态更新按钮名称
					const firstItem = this.DailyOutputList.find(item => item.id === this.selectedItems[0]);
					this.ToExamineShow = true;
					this.ToExamineName = firstItem?.Approve ? '取消审核' : '审核';
				}
			},
			// 修正后的单选方法
			toggleSelect(ite) {
				const index = this.selectedItems.indexOf(ite.id)
				// 审核
				if (index > -1) {
					this.selectedItems.splice(index, 1) // 修正第二个参数为1
					if (this.selectedItems.length === 0) {
						this.ToExamineShow = false
						this.ToExamineName = ''
					}
				} else {
					this.ToExamineShow = true
					this.ToExamineName = ite.Approve == true ? '取消审核' : '审核'
					this.selectedItems.push(ite.id)
				}
			},
			sortrightclose(item) {
				var that = this
				console.log(item);
				if (item.FDailyOutputID) {
					if (item.Approve) {
						that.ApproveButton = '已审核'
					} else {
						that.ApproveButton = '未审核'
					}
					this.queryList(item.FDailyOutputID)
				}
				this.rightshow = false
			},
			rightclose() {
				var that = this

				this.rightshow = false
			},
			rightopen() {

				var that = this
				var show = false
				if (that.baseFormData.JobPROCID) {
					show = true
				}
				if (show) {
					try {
						that.Request.request('getDailyOutputList', {
							JobPROCID: that.baseFormData.JobPROCID
						}, (ret) => {
							console.log(ret);
							if (ret.status == 200) {
								ret.data.ds.map((item, index) => {
									item.BillDate = formatDateTime(item.BillDate)
									item.id = index
								})

								that.DailyOutputList = ret.data.ds
								// that.ReviewShow = ret.data.ds.length > 0 ? true : false
								// var AllList = this.DailyOutputList.filter(item => item.Approve != true)
								// this.selectedItems = AllList.map(item => item.id)
								// this.ToExamineShow = true
								// this.ToExamineName = '审核'
							}
						})
					} catch (e) {
						console.log(e)
						this.$utils.hideLoading();
						this.$utils.msg('请求失败请重试')
					}
				}
			},
			getselfValue(res) {
				let that = this;
				// console.log(res);
				const formDefaults = {
					...res
				};
				if (res.InspectionID !== undefined) {
					formDefaults.InspectionID = res.InspectionID;
				}
				if (res.FQty == '返回') {
					formDefaults.FNgQty = that.baseFormData.FNgQty ? that.baseFormData.FNgQty : 0;
				} else if (res.FQty !== undefined) {
					formDefaults.FNgQty = res.FQty;
					formDefaults.FSumQty = Number(res.FQty) + Number(that.baseFormData.FDailyQtt);

					// formDefaults.NewFNgQty = res.FQty;
				}


				// console.log(formDefaults);
				// 批量更新表单数据（仅在有需要更新的字段时执行）
				if (Object.keys(formDefaults).length > 0) {
					that.assignFormData(that.baseFormData, formDefaults);
				}

			},

			badnum() {
				let that = this;
				var url
				let routes = getCurrentPages();
				if (that.baseFormData.FDailyOutputID) {
					var initData = JSON.parse(JSON.stringify(that.$store.state.GuyueModule.ModuleData_select));
					var parentData = initData[initData.length - 1]
					let queryString = `item=${JSON.stringify(that.baseFormData)}&titleName=刷新`;
					parentData.url = `/st_mes_zs/production/reportingDetail?${queryString}`
					that.$modifyParentData(parentData);
				}
				var obj = {
					path: 'manual',
					Name: '自检详情',
					APPFunID: '自检详情',
					length: routes.length + 1,
					ApproveButton: '保存',
					InspectionID: that.baseFormData.InspectionID ? that.baseFormData.InspectionID : 0,
					ProcedureID: that.baseFormData.ProcedureID,
					JobOrderID: that.baseFormData.JobOrderID ? that.baseFormData.JobOrderID : 0,
					FType: 'ZJ',
					FTypeName: '自检',
					ProcedureName: that.baseFormData.ProcedureName,
					FDailyQtt: that.baseFormData.FDailyQtt ? that.baseFormData.FDailyQtt : 0,
					EquipmentID: that.$store.state.GuyueModule.MesBasicInfo.warehouse.EquipmentID,
					ApproveName: that.baseFormData.ApproveName
				}
				console.log(obj);
				url =
					`/st_mes_zs/production/defectivescrap?obj=${JSON.stringify(obj)}&ApproveButton=${that.ApproveButton}`
				obj.url = url;
				that.GonavigateTo(obj, url)

			},
			GonavigateTo(obj, url) {
				let that = this;
				this.$safeNavigate({
					targetUrl: url, // 目标页面路径
					payload: obj, // 要传递的数据
				});
			},
			pickerConfirm(e) {
				let that = this;

				const formDefaults = {
					SCDate: getFormatDateTime(e.value)
				};
				that.assignFormData(that.baseFormData, formDefaults)
				this.Timeshow = false

			},
			addDefine1() {
				var that = this
				if (!that.readOnlyShow) {
					that.Define1Show = true
					that.Request.request('PGD_GetBGType', {}, (ret) => {
						console.log(ret.data);
						ret.data.ds.map(item => item.name = item.TypeName)
						that.Define1List = ret.data.ds
					})
				}
			},

			addSOP() {
				var that = this
				try {
					that.Request.request('getProductSOP', {
						ProcedureID: that.baseFormData.ProcedureID,
						ProductID: that.baseFormData.ProductID,
						FType: '生产'

					}, (ret) => {
						that.loadingName = '正在打开中…'
						that.showMLoading = true

						if (ret.status == 200) {
							if (ret.data.ds.length > 0 && ret.data.ds[0].FileName) {
								var url = that.Request.IPAgreement() + that.Request.serverIP() + ret.data
									.ds[0].FileName
								console.log(url);
								uni.downloadFile({
									url: url,
									success: function(res) {
										if (res.tempFilePath) {
											var filePath = plus.io.convertLocalFileSystemURL(
												res
												.tempFilePath);
											console.log(JSON.stringify(filePath))
											open.openFile({
												filename: filePath,
												title: 'SOP查看',
												isShowBackIcon: true
											}, ret => {
												that.showMLoading = false
											});
										} else {
											that.changeshowToast()
										}

									}
								})
							} else {
								that.changeshowToast()
							}
						}
					}, (err) => {
						that.showMLoading = false
					})
				} catch (e) {
					console.log(e)
					this.$utils.hideLoading();
					this.$utils.msg('请求失败请重试')
				}
			},
			changeshowToast() {
				var that = this
				that.showMLoading = false
				uni.showToast({
					title: '暂无此文档',
					icon: 'error',
					duration: 2000
				})
			},
			MoludNameclick() {
				var that = this
				that.Request.request('PGD_GetMolud', {
					ProductID: that.baseFormData.ProductID
				}, (ret) => {


					if (ret.status == 200) {
						if (ret.data.ds[0].status == 500) {
							that.showModal('报错', ret.data.ds[0].msg, '确认', '取消');
						} else {
							ret.data.ds.map(item => item.name = item.MoludCode)
							that.MoludList = ret.data.ds
							that.MoludShow = true
						}
					} else {
						that.showModal('报错', ret.data.ds[0].msg, '确认', '取消');
					}
				})
			},
			MoludClick(e) {
				var that = this
				const formDefaults = {
					MoludName: e.name,
					MoludID: e.MoludID
				};
				this.assignFormData(this.baseFormData, formDefaults)
				this.MoludShow = false

			},
			Define1Click(e) {
				var that = this
				const formDefaults = {
					Define1Name: e.name,
					Define1: e.JobDocTypeID
				};
				this.assignFormData(this.baseFormData, formDefaults)
				this.Define1Show = false
				this.$forceUpdate()
			},
			AddPieceTime() {
				var that = this
				if (!that.readOnlyShow) {
					that.PieceTimeShow = true
				}
			},
			AddSCDate() {
				var that = this
				if (!that.readOnlyShow) {
					that.Timeshow = true
				}
			},
			PieceTimeClick(e) {
				var that = this
				const formDefaults = {
					PieceTime1: e.name,
					PieceTime: e.id
				};
				this.assignFormData(this.baseFormData, formDefaults)

				this.PieceTimeShow = false

			},

			ResultClick(e) {
				var that = this
				const formDefaults = {
					ResultName: e.name,
					Result: e.ID
				};
				this.assignFormData(this.baseFormData, formDefaults)

				this.Resultshow = false

			},
			exceptionClick(e) {
				var that = this
				var url
				that.exceptionShow = false

				let routes = getCurrentPages();
				const formDefaults = {};
				let obj = {
					path: 'manual',
					Name: '',
					APPFunID: '',
					length: routes.length
				}

				switch (e.name) {
					case '设备异常':
						obj.Name = '设备异常详情'
						obj.APPFunID = '设备异常详情'
						formDefaults.FaultTypeID = 1
						break;
					case '模具异常':
						obj.Name = '模具异常详情'
						obj.APPFunID = '模具异常详情'
						formDefaults.FaultTypeID = 2
						break;
					case '工艺异常':
						obj.Name = '工艺异常详情'
						obj.APPFunID = '工艺异常详情'
						formDefaults.FaultTypeID = 3
						break;
					case '品质异常':
						obj.Name = '品质异常详情'
						obj.APPFunID = '品质异常详情'
						formDefaults.FaultTypeID = 4
						break;
				}

				if (Object.keys(formDefaults).length > 0) {
					that.assignFormData(that.baseFormData, formDefaults);
				}


				if (e.name == '品质异常') {
					var item = {
						InspectionID: that.baseFormData.InspectionID ? that.baseFormData.InspectionID : 0,
						FType: 'ZJ',
						BillNO: that.baseFormData.BillNO,
						PGBillNo: that.baseFormData.PGBillNo,
						CkAmount: that.baseFormData.FSumQty,
						ProductID: that.baseFormData.ProductID,
						ProductName: that.baseFormData.ProductName,
						JYBillNo: that.baseFormData.BillNO,
						JobOrderID: that.baseFormData.JobOrderID ? that.baseFormData.JobOrderID : 0,

					}
					url = `/st_mes_zs/abnormal/qualityDetails?item=${JSON.stringify(item)}`

				} else {
					url =
						`/st_mes_zs/abnormal/exceptionDetails?DetailObj=${JSON.stringify(that.baseFormData)}&titleName=${e.name}`
				}

				if (that.baseFormData.FDailyOutputID) {
					var initData = JSON.parse(JSON.stringify(that.$store.state.GuyueModule.ModuleData_select));
					var parentData = initData[initData.length - 1]
					let queryString = `item=${JSON.stringify(that.baseFormData)}&titleName=刷新`;
					parentData.url = `/st_mes_zs/production/reportingDetail?${queryString}`
					that.$modifyParentData(parentData);
				}

				obj.url = url
				that.GonavigateTo(obj, url)
			},
			exception() {
				var that = this
				that.exceptionShow = true

			},
			changeResultshow() {
				var that = this
				that.Request.request('getJYResult', {
					FType: '首件检验'
				}, (ret) => {
					console.log(ret.data);
					if (ret.status == 200) {
						that.Resultlist = ret.data.ds
						that.Resultlist.map(item => {
							item.name = item.NAME
						})
						that.Resultshow = true
					}
				})

			},

			JYJGconfirm(e) {
				var name = e.value[0]
				var num
				this.JYJGshow = false
				num = name == '合格' ? 1 : 2
				this.tableData[this.JYJGshowIndex].JYJG = num
				this.tableData[this.JYJGshowIndex].JYJGName = name

			},
			addJYJG(item, index) {
				this.JYJGshow = true
				this.JYJGshowIndex = index
			},
			toexamine() {
				var that = this
				that.showModal('审核', '确定审核吗?', '确认', '取消');
			},
			submit(str) {
				var that = this
				console.log(that.baseFormData);
				var show = true
				var msg

				if (that.baseFormData.FDailyQtt == '' || that.baseFormData.FDailyQtt == null) {
					show = false
					msg = '请输入合格数量'
				} else if (that.baseFormData.FSumQty == '' || that.baseFormData.FSumQty == null) {
					show = false
					msg = '请输入报工数量'
				} else if (!that.baseFormData.PieceTime1) {
					show = false
					msg = '请输入计时计件'
				} else if (!that.baseFormData.FProcessManName) {
					show = false
					msg = '请选择生产人员'
				}
				if (show) {
					that.Request.request('SelectFCJType', {}, (ret) => {

						const formDefaults = {
							FCJType: ret.data.ds[0].FCJType,
							MoludID: 0,
							FNgQty: 0,
							FDailyOutputID: 0,
							FDailyOutputDeID: 0,
							SoOrderDeID: 0,
							SoOrderID: 0,

						};
						that.replaceFormData(that.baseFormData, that.baseFormData, formDefaults);

						console.log(that.baseFormData);
						var obj = JSON.parse(JSON.stringify(that.baseFormData))
						console.log(obj);
						that.Request.request('savePGDDailyOutputBG', obj, (ret) => {
							console.log(ret.data);
							if (ret.data.ds[0].status == 200) {
								that.ApproveButton = '未审核'
								switch (str) {
									case '退出':
										that.AndSetStateData()
										break;
									case '保存':
										that.refreshqueryList('保存成功', ret.data.ds[0].FDailyOutputID)
										break;
								}

							} else {
								that.showModal('报错', ret.data.ds[0].msg, '确认', '取消');

							}
						})
					})
				} else {
					that.showModal('报错', msg, '确认', '取消');
				}
			},
			refreshqueryList(message, FDailyOutputID) {
				var that = this
				that.$refs.uToast.show({
					type: 'success',
					message: message
				})
				setTimeout(() => {
					that.queryList(FDailyOutputID)
				}, 1000)
			},
			changeLevel(list, data, row) {
				console.log(list);
				console.log(data);
				console.log(row);

				if (data.Name == row.Name) {
					that.initData = data
					that.initObj = row
					if (that.ApproveButton == "保存" || that.ApproveButton == "未审核") {
						that.showModal('通知', '当前页面未保存，是否先保存在关闭？', '是,保存并关闭', '否,直接关闭');
					} else {
						that.AndSetStateData()
					}
				} else {
					getchangeLevel(data)
					uni.$emit('refreshList');

				}

			},
			AndSetStateData() {
				var that = this
				that.clearAfterCondition(that.initData, (item) => item
					.APPFunID == that
					.initObj.APPFunID);
				that.$store.commit('GuyueModule/ChangeAndSetStateData', {
					Name1: 'ModuleData_select',
					data: that.initData
				})
				var initData = JSON.parse(JSON.stringify(that.initData));
				parentData = initData[initData.length - 1]
				that.$refs.framework.ToLevel(parentData)
			},
			queryList(id) {
				var that = this
				try {
					that.Request.request('getDailyOutputBGDetail', {
						FDailyOutputID: id
					}, (ret) => {
						console.log(ret);
						that.showMLoading = false
						if (ret.status == 200) {
							var [firstItem] = ret.data.ds;
							var secondItem = ret.data.ds1[0];
							var thirdItem = ret.data.ds2[0];

							var fourthItem = ret.data.ds3.length > 0 ? ret.data.ds3[0] : {};
							that.assignFormData(that.baseFormData, firstItem)
							that.JobPROCID = thirdItem.JobPROCID
							const formDefaults = {
								ApproveTime: formatDateTime(firstItem.ApproveTime),
								OkAmount: firstItem.OkAmount,
								PGBillNo: firstItem.PGBillNo,
								ProductID: secondItem.ProductID,
								ProductName: secondItem.ProductName,
								ReportQty: secondItem.ReportQty,
								FPlanQty: secondItem.FPlanQty,
								NotApproveQty: secondItem.NotApproveQty,
								WCQty: secondItem.WCQty,
								JobPROCID: thirdItem.JobPROCID,
								// FNgQty: that.baseFormData.NewFNgQty ? that.baseFormData.NewFNgQty : firstItem
								// .FNgQty,
								FNgQty: firstItem.FNgQty,
								JobOrderID: firstItem.JobOrderID,
								InspectionID: fourthItem.InspectionID ? fourthItem.InspectionID : 0,
								// NewFNgQty: 0,
							};
							console.log(formDefaults);
							that.assignFormData(that.baseFormData, formDefaults)
							that.assignFormData(that.baseFormDataList, firstItem);
							const {
								ApproveName,
							} = that.baseFormData;
							that.readOnlyShow = ApproveName === '已审核' ? true : false;
							that.ApproveButton = ApproveName === '已审核' ? '已审核' : '未审核';

						}

					}, (err) => {
						that.showMLoading = false
					})
				} catch (e) {
					that.showMLoading = false
					console.log(e)
					this.$utils.hideLoading();
					this.$utils.msg('请求失败请重试')
				}
			},


			clearAfterCondition(data, condition) {
				// 遍历数组找到第一个满足条件的元素的索引  
				for (let i = 0; i < data.length; i++) {
					if (condition(data[i])) {
						console.log(i);
						// 如果找到，则截断数组  
						data.splice(i); // 注意：splice 会修改原数组  
						break;
					}
				}
			},
		}
	}
</script>

<style lang="scss" >
	@import "../css/index.css";

	.rightshowView {
		width: 70vw !important;

		.tableTow {
			height: 80vh;
			overflow-y: auto;

			table {
				width: 70vw;
			}
		}

		.u-popup——view {
			margin: 1% 1% 0 0;
			margin-left: auto;

			width: 15%;

			.u-button {
				// display: inline-block;
				color: #fff;
				background-color: #51d0d0;
				width: 100%;
				font-size: 18px;
				border: none;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}
	}

	.td_view {
		display: flex;
		align-items: center;
		border: none;

		text {
			font-size: 16px;
			display: inline-block;
			width: 100%;
		}

		.SOPView {
			flex: 1;
			box-sizing: border-box;

			.u-button {
				width: 10%;
				float: right;
				color: #fff;
				background-color: #51d0d0;
				box-sizing: border-box;
			}
		}
	}



	.bottomBtnsAll {
		padding: 1%;
		display: flex;
		background-color: #fff;

		button {
			display: inline-block;
			color: #fff;
			background-color: #51d0d0;
			width: 15%;
			font-size: 18px;
		}

		.button0 {
			background-color: #ffce04;
		}

		.button1 {
			background-color: red;
		}

		.button3 {
			width: 30%;
		}
	}


	.arrow_left {
		position: fixed;
		bottom: 44.5%;
		right: 1px;
	}

	/* 隐藏复选框 */
	.no-checkbox .uni-checkbox {
		display: none !important;
	}

	/* 调整行内布局补偿空间 */
	.no-checkbox .uni-td:first-child {
		padding-left: 15px;
		/* 根据实际布局调整 */
	}

	/* 修复复选框样式 */
	checkbox .wx-checkbox-input,
	checkbox .uni-checkbox-input {
		// border-radius: 50% !important;
		transform: scale(0.9);
	}

	checkbox .wx-checkbox-input.wx-checkbox-input-checked,
	checkbox .uni-checkbox-input.uni-checkbox-input-checked {
		background: #007aff !important;
		border-color: #007aff !important;
	}
</style>